package servlet;

import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;

//import persistence.CustomerDao;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

/**
 * Servlet implementation class UploadImage
 */
@WebServlet("/UploadImage")
public class UploadImage extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request,response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		SmartUpload su = new SmartUpload();
		PageContext pageContext=JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true, 8192, true);
		su.initialize(pageContext);  	
		
		String realAddress = null;
		String imgName = null;
		
		try {
			su.setAllowedFilesList("jpg,jpeg,bmp,png,JPG,JPEG,BMP,PNG");
			su.upload();
		} catch (Exception e) {			
			return;
		}
		Random random = new Random(System.currentTimeMillis());
		imgName = String.valueOf(random.nextLong())+"."+su.getFiles().getFile(0).getFileExt();
		realAddress = this.getServletContext().getRealPath("")+"\\userimages\\"+imgName;
		File dirFile = new File(this.getServletContext().getRealPath("")+"\\userimages\\");
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}
		System.out.println(realAddress);

		try {
			su.getFiles().getFile(0).saveAs(realAddress);
		} catch (SmartUploadException e) {
			e.printStackTrace();
		}
		
		String path = "userimages\\"+imgName;

		String[] buffer = path.split("\\\\");
		StringBuffer strBuf = new StringBuffer(buffer[0]);
		for (int i = 1; i < buffer.length; i++) {
			strBuf.append("\\\\\\\\");
			strBuf.append(buffer[i]);
		}
		String printStr="<script>parent.setImagePath('"+strBuf.toString()+"')</script>";
		
		System.out.print(printStr);
		response.getWriter().println(printStr);
	}

}
